/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.funda.xmppserver.handlers.iqhandlers;

import com.funda.xmppserver.ComponentParser;
import com.funda.xmppserver.JID;
import com.funda.xmppserver.XMPPClient;
import com.funda.xmppserver.XMPPInfo;
import com.funda.xmppserver.usermanager.Users;
import com.funda.xmppserver.writer.XMPPPacketWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;

/**
 *
 * @author kurinchi
 */
public class IQBindHandler implements ComponentParser {

    XMPPPacketWriter packetwriter;
    XMPPClient client;
    Connection conn;
    Statement smt;
    ResultSet rs;
    Boolean valid = true;
    String id;
    String type;
    JID jid;

    public IQBindHandler(XMPPPacketWriter packetwriter, XMPPClient client, String id, String type) {
        this.packetwriter = packetwriter;
        this.client = client;
        this.id = id;
        this.type = type;
        jid = client.getJid();


    }

    public void parseElement(XMLStreamReader xmlReader) throws XMLStreamException {
        System.out.println("IQBind...");

        if (xmlReader.getNamespaceURI(0).equalsIgnoreCase("urn:ietf:params:xml:ns:xmpp-bind")) {
            System.out.println("bind uri");
        }
        while (xmlReader.hasNext()) {
            xmlReader.next();
            int event = xmlReader.getEventType();
            System.out.println("" + event);
            if (event == XMLEvent.START_ELEMENT && xmlReader.getLocalName().equalsIgnoreCase("resource")) {
                System.out.println("resource");
                break;
            }
        }

        String resourcetxt = xmlReader.getElementText();

        String resource = resourcetxt + UUID.randomUUID().toString();
        jid.setUsername(client.getUsername());
        jid.setServicename(XMPPInfo.getHOST());
        jid.setResource(resource);

        ArrayList rsrc = client.getResource();
        rsrc.add(resource);
        client.setResource(rsrc);

        System.out.println("jid : " + client.getUsername() + "@" + XMPPInfo.getHOST() + "/" + resource);

        String clientjid = client.getUsername() + "@" + XMPPInfo.getHOST() + "/" + resource;
        Users.getUserlist().put(clientjid, client);

        Map jids = Users.getUserjidlist();
        List list;
        if (jids.containsKey(client.getUsername())) {
            list = (List) jids.get(client.getUsername());
            list.add(clientjid);

        } else {
            list=new LinkedList();
            list.add(clientjid);

        }
        Users.getUserjidlist().put(client.getUsername(), list);
        packetwriter.sendbindResponse(id, clientjid);
    }
}
